package com.clg.user;

import com.clg.common.beans.SessionUser;
import com.clg.common.constants.Constants;
import com.clg.common.model.User;
import com.clg.common.tools.MessageTools;
import com.clg.common.tools.RetRes;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;

import javax.security.auth.login.LoginException;

/**
 * 登录
 * Created by usercai on 2016/9/26.
 */
public class LoginController extends Controller{
    // LoginInterceptor 已被Clear清除掉，不会被其拦截
    @Clear
    public void index() {
        render("login/login.html");
    }

    /**
     * 登录
     */
    @Clear
    @Before(LoginValidator.class)
    public void loginSubmit(){
        String loginName = getPara("loginName");
        String password = getPara("passWord");

        LoginService loginService = Enhancer.enhance(LoginService.class);
        RetRes ret = loginService.loginAuth(loginName,password);
        if(!ret.isSuccess()){
            MessageTools.setError(ret.getMessage());
            keepPara("loginName");
            render("login/login.html");
            return;
        }

        setSessionAttr(Constants.USER_SESSION_KEY,new SessionUser((User)ret.get("user")));
        redirect("/home");
    }

    /***
     *  登出
     */
    public void loginOut(){
        removeSessionAttr(Constants.USER_SESSION_KEY);
        redirect("/login");
    }
}
